# -*- coding: utf-8 -*-
# @Time    : 2019-12-16 19:28
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : R27_IC_NonExternalGuaranteeAssetsDisposalAndBadDebtsAndGuarantorCompensationCheck_WHB_2D.py
# @Software: PyCharm

'''eof
name:申请人5年内信贷业务资产处置、呆账、保证人代偿笔数校验
code:R27_IC_NonExternalGuaranteeAssetsDisposalAndBadDebtsAndGuarantorCompensationCheck_WHB_2D
tableName:
columnName:
groups:弱规则>个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import sys
import re
import datetime
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :return:该表全部数据
        '''
    table = data.get(tableName)
    if occurTimes == 0:
        if table is None:
            return [{}]
        elif table == "":
            return ""
        elif isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)
    if occurTimes == 1:
        if table == "":
            return ""
        elif table is None or isinstance(table, list) is False or len(table) == 0:
            return None
        else:
            return data.get(tableName)


def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False


def R27_IC_NonExternalGuaranteeAssetsDisposalAndBadDebtsAndGuarantorCompensationCheck_WHB_2D():
    factor1 = factor2 = factor3 = factor4 = []
    data = IC_DSJ_2D['data']
    # 信贷交易信息概要信息
    PCO = getTable(data, 'PCO', 1)
    if PCO is None:
        factor1.append(None)
        factor2.append(None)
    elif PCO == "":
        factor1.append(0)
        factor2.append(0)
    else:
        PC02 = getTable(PCO[0], 'PC02', 0)
        if PC02 is None:
            factor1.append(None)
            factor2.append(None)
        elif PC02 == [{}] or PC02 == "":
            factor1.append(0)
            factor2.append(0)
        else:
            # 信贷交易信息概要信息（PC02）·呆账汇总信息段（PC02C）·账户数（PC02CS01）
            PC02C = getTable(PC02[0], 'PC02C', 0)
            if PC02C is None or PC02C == "":
                factor1.append(None)
            elif PC02C == [{}]:
                factor1.append(0)
            else:
                PC02CS01 = PC02C[0].get('PC02CS01')
                if isfloat(PC02CS01):
                    factor1.append(float(PC02CS01))
                else:
                    factor1.append(None)
            # 信贷交易信息概要信息（PC02）·被追偿汇总信息段（PC02B）·被追偿汇总信息（PC02BH）·业务类型（PC02BD01）为1（资产处置业务）的次数；
            PC02B = getTable(PC02[0], 'PC02B', 0)
            if PC02B is None or PC02B == "":
                factor2.append(None)
            elif PC02B == [{}]:
                factor2.append(0)
            else:
                PC02BH = getTable(PC02B[0], 'PC02BH', 1)
                if PC02BH is None or PC02BH == "":
                    factor2.append(None)
                else:
                    for PC02BH_Items in PC02BH:
                        try:
                            PC02BD01 = PC02BH_Items.get('PC02BD01')
                            if PC02BD01 in null_type_list:
                                factor2.append(None)
                            elif PC02BD01 == '1':
                                factor2.append(1)
                            else:
                                factor2.append(0)
                        except:
                            factor2.append(None)
                            continue
    # 借贷账户信息单元（PD01）·基本信息段（PD01A）·业务种类（PD01AD03）为A1（资产处置)、B1(代偿债务 )的次数之和
    PDA = getTable(data, 'PDA', 1)
    if PDA is None:
        factor3.append(None)
    elif PDA == "":
        factor3.append(0)
    else:
        PD01 = getTable(PDA[0], 'PD01', 0)
        if PD01 is None or PD01 == "":
            factor3.append(None)
        elif PD01 == [{}]:
            factor3.append(0)
        else:
            for PD01_Items in PD01:
                try:
                    PD01A = getTable(PD01_Items, 'PD01A', 1)
                    if PD01A is None or PD01A == "":
                        factor3.append(None)
                    else:
                        PD01AD03 = PD01A[0].get('PD01AD03')
                        if PD01AD03 in ['A1', 'B1']:
                            factor3.append(1)
                        else:
                            factor3.append(0)
                except:
                    factor3.append(None)
                    continue
    #相关还款责任信息单元（PD03）·相关还款责任汇总信息段（PD03A）·主借款人身份类别（PD03AD08）为1(自然人)其业务种类（PD03AD02）为A1(资产处置)、B1(代偿债务)；主借款人身份类别（PD03AD08）为 2(组织机构)其业务种类（PD03AD02）为51(资产处置)的次数之和
    PCR  = getTable(data, 'PCR', 1)
    if PCR is None:
        factor4.append(None)
    elif PCR == "":
        factor4.append(0)
    else:
        PD03 = getTable(PCR[0], 'PD03', 0)
        if PD03 is None or PD03 == "":
            factor4.append(None)
        elif PD03 == [{}]:
            factor4.append(0)
        else:
            for PD03_Items in PD03:
                try:
                    PD03A = getTable(PD03_Items, 'PD03A', 1)
                    if PD03A is None or PD03A == "":
                        factor4.append(None)
                    else:
                        PD03AD08 = PD03A[0].get('PD03AD08')
                        PD03AD02 = PD03A[0].get('PD03AD02')
                        if PD03AD08 in null_type_list or PD03AD02 in null_type_list:
                            factor4.append(None)
                        elif (PD03AD08 == '1' and PD03AD02 in ['A1', 'B1'] ) or PD03AD08 == '2' and PD03AD02 == '51':
                            factor4.append(1)
                        else:
                            factor4.append(0)
                except:
                    factor4.append(None)
                    continue

    factor1NotNone = filter(lambda x: x is not None, factor1)
    factor2NotNone = filter(lambda x: x is not None, factor2)
    factor3NotNone = filter(lambda x: x is not None, factor3)
    factor4NotNone = filter(lambda x: x is not None, factor4)
    if len(factor1NotNone)==len(factor2NotNone)==len(factor3NotNone)==len(factor4NotNone) == 0:
        return u'缺失值'
    else:
        return max(sum(factor1NotNone), sum(factor2NotNone), sum(factor3NotNone), sum(factor4NotNone))

result = R27_IC_NonExternalGuaranteeAssetsDisposalAndBadDebtsAndGuarantorCompensationCheck_WHB_2D()